package cn.jiyun.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.system.UserInfo;
import cn.jiyun.pojo.UsersInfo;
import cn.jiyun.service.UserInfoService;
import cn.jiyun.util.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public class UserInfoController {
    private final static Logger logger = LoggerFactory.getLogger(UserInfoController.class);


    @Autowired
    private UserInfoService userInfoService;


    @GetMapping("/pagePath/{page}")
    public String showPage(@PathVariable String page) {

        return page;
    }


    @PostMapping("/register")
    @ResponseBody
    public Object register(UsersInfo usersInfo) {
        String userName = usersInfo.getUserName();
        String password = usersInfo.getPassword();
        Integer userAge = usersInfo.getAge();
        String phone = usersInfo.getPhone();
        if (phone == null || phone.length() != 11) {

            return "手机号不正确";
        }
        boolean b = checkUser(phone);
        if (b) {
            return "用户名已存在";
        }

        if (StringUtils.isEmpty(userName)) {
            return "用户名不能为空";
        }
        if (StringUtils.isEmpty(password)) {
            return "密码不能为空";
        }
        if (userAge == null || userAge <= 0) {
            return "用户年龄不正确";
        }

        //密码加密存储
        String newPassword = SecureUtil.md5(password);
        usersInfo.setPassword(newPassword);
        logger.info("用户注册信息:{}", usersInfo.toString());
        userInfoService.register(usersInfo);
        return "注册成功";

    }


    @GetMapping("/queryLists")
    @ResponseBody
    public PageResult<UserInfo> queryList(Integer pageIndex, Integer pageSzie) {
        if (pageIndex == null || pageIndex <= 0) {
            pageIndex = 1;
        }
        if (pageSzie == null || pageSzie <= 0) {
            pageSzie = 5;
        }

        PageResult<UserInfo> userInfoPageResult = userInfoService.queryList(pageIndex, pageSzie);
        return userInfoPageResult;

    }

    @GetMapping("/queryUserByName")
    @ResponseBody
    public Object queryUserByName(String username) {

        if (StringUtils.isEmpty(username)) {
            return "用户名不能为null";
        }
        return userInfoService.queryUser(username);
    }


    public boolean checkUser(String phone) {
        return userInfoService.checkUserByPhone(phone);
    }

}
